import 'dart:io';
import 'dart:convert';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:open_filex/open_filex.dart';
import 'package:dio/dio.dart';
import 'package:fishing/models/app_version.dart';
import 'package:fishing/services/http_client.dart';
import 'package:fishing/utils/storage_util.dart';

class VersionService {
  static const String _lastCheckKey = 'last_version_check';
  static const String _skipVersionKey = 'skip_version';
  static const String _downloadedApkKey = 'downloaded_apk_info';
  
  final HttpClient _httpClient = HttpClient();

  /// 检查版本更新
  Future<CheckUpdateResponse> checkUpdate({bool forceCheck = false}) async {
    try {
      // 如果不是强制检查，检查是否需要跳过
      if (!forceCheck && await _shouldSkipCheck()) {
        return CheckUpdateResponse(hasUpdate: false);
      }

      final request = await _buildCheckUpdateRequest();
      
      final response = await _httpClient.post(
        '/pond/app/version/check-update',
        data: request.toJson(),
      );

      if (response['code'] == 200) {
        final updateResponse = CheckUpdateResponse.fromJson(response['data'] ?? {});
        
        // 记录检查时间
        await StorageUtil.setValue(_lastCheckKey, DateTime.now().toIso8601String());
        
        return updateResponse;
      } else {
        throw Exception(response['msg'] ?? '检查更新失败');
      }
    } catch (e) {
      return CheckUpdateResponse(
        hasUpdate: false,
        message: '检查更新失败: $e',
      );
    }
  }

  /// 记录更新日志
  Future<void> recordUpdateLog({
    required String targetVersion,
    required String updateStatus,
    String? errorMessage,
  }) async {
    try {
      final packageInfo = await PackageInfo.fromPlatform();
      final deviceInfo = await _getDeviceInfo();
      
      final logData = {
        'deviceId': deviceInfo['deviceId'],
        'currentVersion': packageInfo.version,
        'targetVersion': targetVersion,
        'updateStatus': updateStatus,
        'errorMessage': errorMessage,
        'platform': Platform.isAndroid ? 'android' : 'ios',
        'deviceModel': deviceInfo['deviceModel'] ?? 'unknown',
        'osVersion': deviceInfo['osVersion'] ?? 'unknown',
      };

      await _httpClient.post(
        '/pond/app/version/update-log',
        data: logData,
      );
    } catch (e) {
    }
  }

  /// 构建检查更新请求
  Future<CheckUpdateRequest> _buildCheckUpdateRequest() async {
    final packageInfo = await PackageInfo.fromPlatform();
    final deviceInfo = await _getDeviceInfo();
    
    return CheckUpdateRequest(
      deviceId: deviceInfo['deviceId'] ?? 'unknown',
      currentVersion: packageInfo.version,
      buildNumber: int.tryParse(packageInfo.buildNumber) ?? 1, // 发送buildNumber，避免后端验证失败
      platform: Platform.isAndroid ? 'android' : 'ios',
      deviceModel: deviceInfo['deviceModel'] ?? 'unknown',
      osVersion: deviceInfo['osVersion'] ?? 'unknown',
    );
  }

  /// 获取设备信息
  Future<Map<String, String>> _getDeviceInfo() async {
    final deviceInfoPlugin = DeviceInfoPlugin();
    
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfoPlugin.androidInfo;
      return {
        'deviceId': androidInfo.id,
        'deviceModel': '${androidInfo.brand} ${androidInfo.model}',
        'osVersion': 'Android ${androidInfo.version.release}',
      };
    } else if (Platform.isIOS) {
      final iosInfo = await deviceInfoPlugin.iosInfo;
      return {
        'deviceId': iosInfo.identifierForVendor ?? 'unknown',
        'deviceModel': '${iosInfo.name} ${iosInfo.model}',
        'osVersion': 'iOS ${iosInfo.systemVersion}',
      };
    } else {
      return {
        'deviceId': 'unknown',
        'deviceModel': 'unknown',
        'osVersion': 'unknown',
      };
    }
  }

  /// 检查是否应该跳过检查
  Future<bool> _shouldSkipCheck() async {
    // 检查上次检查时间，如果距离上次检查不到1小时，跳过
    final lastCheckStr = await StorageUtil.getValue(_lastCheckKey);
    if (lastCheckStr != null) {
      final lastCheck = DateTime.parse(lastCheckStr);
      final now = DateTime.now();
      if (now.difference(lastCheck).inHours < 1) {
        return true;
      }
    }

    return false;
  }

  /// 设置跳过某个版本
  Future<void> skipVersion(String version) async {
    await StorageUtil.setValue(_skipVersionKey, version);
  }

  /// 检查是否跳过了某个版本
  Future<bool> isVersionSkipped(String version) async {
    final skippedVersion = await StorageUtil.getValue(_skipVersionKey);
    return skippedVersion == version;
  }

  /// 清除跳过版本记录
  Future<void> clearSkippedVersion() async {
    await StorageUtil.removeValue(_skipVersionKey);
  }

  /// 清理旧的APK文件
  Future<void> cleanOldApkFiles() async {
    try {
      // 获取下载目录
      final directory = await getApplicationDocumentsDirectory();
      final dirList = directory.listSync();
      
      // 查找所有APK文件
      final apkFiles = dirList.where((file) => 
        file is File && file.path.toLowerCase().endsWith('.apk')
      ).cast<File>();
      
      
      // 获取当前缓存的APK信息
      final downloadedInfoStr = await StorageUtil.getValue(_downloadedApkKey);
      String? currentApkPath;
      if (downloadedInfoStr != null) {
        try {
          final info = Map<String, dynamic>.from(jsonDecode(downloadedInfoStr));
          currentApkPath = info['filePath'] as String?;
        } catch (e) {
        }
      }
      
      // 删除除当前缓存APK之外的所有APK文件
      for (final file in apkFiles) {
        if (file.path != currentApkPath) {
          try {
            await file.delete();
          } catch (e) {
          }
        }
      }
    } catch (e) {
    }
  }

  /// 清除所有下载缓存
  Future<void> clearDownloadCache() async {
    try {
      await StorageUtil.removeValue(_downloadedApkKey);
      await cleanOldApkFiles();
    } catch (e) {
    }
  }

  /// 检查是否已下载过APK文件
  Future<String?> getDownloadedApkPath(String downloadUrl, String fileName, {int? expectedFileSize}) async {
    try {
      // 获取已下载的APK信息
      final downloadedInfoStr = await StorageUtil.getValue(_downloadedApkKey);
      if (downloadedInfoStr != null) {
        try {
          final info = Map<String, dynamic>.from(jsonDecode(downloadedInfoStr));
        
        // 检查URL和文件名是否匹配
        if (info['downloadUrl'] == downloadUrl && info['fileName'] == fileName) {
          final filePath = info['filePath'] as String;
          final file = File(filePath);
          
          // 检查文件是否仍然存在
          if (await file.exists()) {
            // 如果提供了预期文件大小，验证文件完整性
            if (expectedFileSize != null) {
              final actualSize = await file.length();
              if (actualSize != expectedFileSize) {
                await file.delete();
                await StorageUtil.removeValue(_downloadedApkKey);
                return null;
              }
            }
            
            return filePath;
          } else {
            // 清除无效的缓存信息
            await StorageUtil.removeValue(_downloadedApkKey);
          }
        } else {
          // 清除旧的缓存信息
          await StorageUtil.removeValue(_downloadedApkKey);
        }
        } catch (e) {
          // 清除无效的缓存信息
          await StorageUtil.removeValue(_downloadedApkKey);
        }
      }
      
      return null;
    } catch (e) {
      return null;
    }
  }

  /// 保存已下载的APK信息
  Future<void> saveDownloadedApkInfo(String downloadUrl, String fileName, String filePath) async {
    try {
      final file = File(filePath);
      final fileSize = await file.length();
      
      final info = {
        'downloadUrl': downloadUrl,
        'fileName': fileName,
        'filePath': filePath,
        'fileSize': fileSize,
        'downloadTime': DateTime.now().toIso8601String(),
      };
      await StorageUtil.setValue(_downloadedApkKey, jsonEncode(info));
    } catch (e) {
    }
  }

  /// 下载APK文件（带缓存检查）
  Future<String> downloadApk(
    String downloadUrl,
    String fileName, {
    Function(double)? onProgress,
    int? expectedFileSize,
  }) async {
    try {
      // 首先检查是否已经下载过这个文件
      final cachedPath = await getDownloadedApkPath(downloadUrl, fileName, expectedFileSize: expectedFileSize);
      if (cachedPath != null) {
        // 立即回调100%进度，表示已完成
        if (onProgress != null) {
          onProgress(1.0);
        }
        return cachedPath;
      }
      
      
      // 请求存储权限
      if (Platform.isAndroid) {
        var status = await Permission.storage.status;
        
        if (!status.isGranted) {
          status = await Permission.storage.request();
          
          if (!status.isGranted) {
            // Android 11+ 可能需要管理外部存储权限
            final manageStatus = await Permission.manageExternalStorage.request();
            
            if (!manageStatus.isGranted && !status.isGranted) {
              throw Exception('需要存储权限才能下载更新文件');
            }
          }
        }
      }

      // 获取下载目录
      final directory = await getApplicationDocumentsDirectory();
      final filePath = '${directory.path}/$fileName';

      // 删除已存在的文件
      final file = File(filePath);
      if (await file.exists()) {
        await file.delete();
      }

      // 使用Dio下载文件
      final dio = Dio();
      await dio.download(
        downloadUrl,
        filePath,
        onReceiveProgress: (received, total) {
          if (total != -1 && onProgress != null) {
            final progress = received / total;
            onProgress(progress);
          }
        },
      );

      // 保存下载信息到缓存
      await saveDownloadedApkInfo(downloadUrl, fileName, filePath);
      
      return filePath;
    } catch (e) {
      throw Exception('下载失败: $e');
    }
  }

  /// 安装APK文件
  Future<bool> installApk(String filePath) async {
    try {
      if (!Platform.isAndroid) {
        throw Exception('只支持Android平台的APK安装');
      }

      final file = File(filePath);
      if (!await file.exists()) {
        throw Exception('APK文件不存在');
      }

      // 检查并请求安装权限
      final installPermission = await Permission.requestInstallPackages.status;
      
      if (!installPermission.isGranted) {
        final result = await Permission.requestInstallPackages.request();
        
        if (!result.isGranted) {
          if (result.isPermanentlyDenied) {
            throw Exception('安装权限被永久拒绝，请在设置中手动开启');
          } else {
            throw Exception('需要安装权限才能安装更新');
          }
        }
      }

      // 使用open_filex打开APK文件进行安装
      final result = await OpenFilex.open(filePath);
      
      return result.type == ResultType.done;
    } catch (e) {
      throw Exception('安装失败: $e');
    }
  }

  /// 获取当前应用版本信息
  Future<Map<String, String>> getCurrentVersionInfo() async {
    final packageInfo = await PackageInfo.fromPlatform();
    return {
      'version': packageInfo.version,
      'buildNumber': packageInfo.buildNumber,
      'appName': packageInfo.appName,
      'packageName': packageInfo.packageName,
    };
  }
}